package com.origin.niuke.stack;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * NC241 计算器(二)
 * 算法：栈
 *
 * @author yezh
 * @date 2023/1/4 20:18
 */
public class NC241 {

    public static void main(String[] args) {
        System.out.println(new NC241().calculate("8*9-19"));
    }

    public int calculate(String s) {
        // write code here
        Deque<Integer> num = new ArrayDeque<>();
        Deque<Character> operator = new ArrayDeque<>();
        int idx = 0, len = s.length();
        while (idx < len) {
            char c = s.charAt(idx);
            if (c >= '0' && c <= '9') {
                int cur = 0;
                while (idx < len && Character.isDigit(s.charAt(idx))) {
                    cur = cur * 10 + (s.charAt(idx) - '0');
                    ++idx;
                }
                if (!operator.isEmpty() && (operator.peekFirst() == '*' || operator.peekFirst() == '/')) {
                    c = operator.pop();
                    int pre = num.pop();
                    if (c == '*') pre *= cur;
                    else pre /= cur;
                    cur = pre;
                }
                num.addFirst(cur);
            } else {
                operator.addFirst(c);
                ++idx;
            }
        }
        int ans = num.pollLast();
        while (!operator.isEmpty()) {
            char c = operator.pollLast();
            int first = num.pollLast();
            if (c == '+') ans += first;
            else ans -= first;
        }
        return ans;
    }

}
